package com.ksyun.campus.metaserver.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ZooKeeper configuration for providing CuratorFramework bean
 */
@Slf4j
@Configuration
public class ZooKeeperConfig {
    
    @Autowired
    private MinfsProperties properties;
    
    @Bean
    public CuratorFramework curatorFramework() {
        log.info("Creating CuratorFramework bean");
        
        // Create retry policy
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(
                properties.getZookeeper().getRetry().getBaseSleepTime(),
                properties.getZookeeper().getRetry().getMaxRetries()
        );
        
        // Create curator client
        CuratorFramework curator = CuratorFrameworkFactory.newClient(
                properties.getZookeeper().getConnectionString(),
                properties.getZookeeper().getSessionTimeout(),
                properties.getZookeeper().getConnectionTimeout(),
                retryPolicy
        );
        
        curator.start();
        
        // Wait for connection
        try {
            curator.blockUntilConnected();
            log.info("CuratorFramework connected to ZooKeeper");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("Interrupted while waiting for ZooKeeper connection", e);
            throw new RuntimeException("Failed to connect to ZooKeeper", e);
        }
        
        return curator;
    }
}
